package it.pir.es02ChatTCP;

import java.io.*;
import java.net.*;

public class ClientObj extends Client {
	
	private ObjectOutputStream objectOutputStream;

	public ClientObj(String nickname, String address, int port) throws UnknownHostException, IOException {
		super(nickname, address, port);
	}
	
	@Override
	protected void connect() throws IOException {
		socket = new Socket(address, port);
		objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
		Message authentication = new Message(nickname, "", Message.AUTHENTICATION);
		sendMessage(authentication);
	}

	@Override
	public void sendMessage(Message message) throws IOException {
		objectOutputStream.writeObject(message);
		objectOutputStream.flush();
	}

	@Override
	public void run() {
		ObjectInputStream objectInputStream;
		try {
			objectInputStream = new ObjectInputStream(socket.getInputStream());
			while(true) {
				reply=(Message)objectInputStream.readObject();
				System.out.println(reply.getNickname() + ": "+ reply.getMessage());
			}
		} catch (IOException e) {
			System.out.println("ERRORE! Problemi di comunicazione con il server!");
			e.printStackTrace();
			// Il programma termina perché il nome utente è già in uso
			System.exit(1);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		
	}

}
